//
//  CMDBDetailHeaderView.swift
//  CMDB
//
//  Created by 曹桂祥 on 17/4/14.
//  Copyright © 2017年 CMDB. All rights reserved.
//

import UIKit

private let picViewWH : CGFloat = (CMDB_Screen_Width - 2 * KleftMargin - 5 * 2) / 3

private let rowCount : Int      = 3

private let picMargin : CGFloat = 5

private let maxTotalWidth : Int = 270

class CMDBDetailHeaderView: CMDBBaseView {
    
    var iconImageView : UIImageView  = UIImageView.getInstance()
    
    var nameLabel : UILabel          = UILabel.getInstance()
    
    var timeLabel : UILabel          = UILabel.getInstance()
    
    var contentLabel : UILabel       = UILabel.getInstance()
    
    var separateView  : UIView       = UIView.getInstance()
    
    var picsView      : UIView       = UIView.getInstance()
    
    var likedView     : UIView       = UIView.getInstance()
    
    var likeBtnImage : UIButton      = UIButton.getInstance()
    
    var contentSize : CGSize?
    
    let btnWidth : CGFloat           = CMDB_Screen_Width / 4
    
    var pictureViewH : CGFloat       = 0
    
    var thisHeight : CGFloat         = 0
    
    var showAllComHeight : CGFloat   = 0
    
    var showLikeViewHeight : CGFloat = 0
    
    var showAllComView : UIView      = UIView.getInstance()
    
    
    
    override func buildSubViews() {
        super.buildSubViews()
        
        iconImageView.frame               = CGRect(x: KleftMargin, y: KleftMargin, width: 40, height: 40)
        
        iconImageView.layer.cornerRadius  = 5
        
        iconImageView.layer.masksToBounds = true
        
        addSubview(iconImageView)
        
        nameLabel.frame                   = CGRect(x: CGRectGetMaxX(self.iconImageView.frame) + KleftMargin, y: KleftMargin, width: 100, height: 16)
        nameLabel.font                    = CMDB_16_Bold_FONT
        
        addSubview(nameLabel)
        
        timeLabel.font                    = CMDB_12_FONT
        timeLabel.textColor               = word38Color
        timeLabel.sizeToFit()
        
        addSubview(timeLabel)
        
        contentLabel.numberOfLines        = 0
        
        contentLabel.font                 = CMDB_16_FONT
        
        contentLabel.textColor            = word87Color
        
        addSubview(contentLabel)
        
        likeBtnImage                  = UIButton()
        
        likeBtnImage.setImage(UIImage(named: "赞-选中"), forState: .Normal)
        
        likeBtnImage.setTitle("   ", forState: .Normal)
        
        likeBtnImage.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0)
        
        likeBtnImage.setTitleColor(word87Color, forState: .Normal)
        
        likeBtnImage.titleLabel?.font    = CMDB_12_FONT
        
        likeBtnImage.sizeToFit()
        
        likeBtnImage.frame                = CGRect(x: 15, y: 10, width: likeBtnImage.width, height: 20)
        
        likedView.addSubview(likeBtnImage)
        
        let moreLikeBtn                   = UIButton()
        
        moreLikeBtn.setImage(UIImage(named:"进入"), forState: .Normal)
        
        moreLikeBtn.setImage(UIImage(named:"进入 copy"), forState: .Highlighted)
        
        moreLikeBtn.sizeToFit()
        
        moreLikeBtn.frame                 = CGRect(x: CMDB_Screen_Width - 25, y: 10, width: moreLikeBtn.width, height: moreLikeBtn.height)
        
        likedView.addSubview(moreLikeBtn)
        
        let lineView                      = UIView.getInstance()
        
        lineView.backgroundColor          = word12Color
        
        lineView.frame                    = CGRect(x: 0, y: 0, width: CMDB_Screen_Width, height: 0.5)
        
        likedView.addSubview(lineView)
        
        likedView.backgroundColor         = UIColor.whiteColor()
        
        addSubview(likedView)
        
        separateView.backgroundColor      = UIColor.Hex6(0xf2f2f2)
        
        addSubview(separateView)
        
        showAllComView.backgroundColor    = UIColor.whiteColor()
        
        let showALlCommLabel = UILabel.getInstance()
        
        showALlCommLabel.text = "全部评论"
        
        showALlCommLabel.font = CMDB_13_FONT
        
        showALlCommLabel.textColor = word87Color
        
        showALlCommLabel.sizeToFit()
        
        showAllComView.addSubview(showALlCommLabel)
        
        showALlCommLabel.snp_makeConstraints { (make) in
            make.left.equalTo(20);
            make.centerY.equalTo(showAllComView)
        }
        
        addSubview(showAllComView)
        
        let showlineView                  = UIView.getInstance()
        
        showlineView.backgroundColor      = word12Color
        
        showAllComView.addSubview(showlineView)
        
        
        showlineView.snp_makeConstraints { (make) in
            make.left.equalTo(0);
            make.right.equalTo(0);
            make.bottom.equalTo(0);
            make.height.equalTo(0.5)
        }
    }
    
    override func update(data: AnyObject?) {
        let topicData = data as! CMDBDynamicBean
        
        
        likeBtnImage.setTitle(topicData.likeCount, forState: .Normal)
        
        iconImageView.setHeader(topicData.user?.icon)
        
        nameLabel.text      = topicData.user?.name
        
        timeLabel.text      = topicData.createTimeFormat
        
        timeLabel.sizeToFit()
        
        timeLabel.frame = CGRect(x: CMDB_Screen_Width - KleftMargin - timeLabel.width, y: 20, width: timeLabel.width, height: timeLabel.height)
        
        contentLabel.text   = topicData.content
        
        contentSize         = topicData.content.suitToSize(CGSize(width: CMDB_Screen_Width - 2 * KleftMargin,height: 999), fontSize: 16, lineSpacing: 2)
        
        contentLabel.frame  = CGRect(x: KleftMargin, y: CGRectGetMaxY(self.iconImageView.frame) + 0.5 * KleftMargin, width: CMDB_Screen_Width - 2 * KleftMargin, height: contentSize!.height)
        
        
        if !topicData.imgs.isEmpty {
            
            picsView.removeFromSuperview()
            
            setupPictureView(topicData.imgs)
            
        }else {
            
            picsView.hidden = true
            
            picsView.frame = CGRect(x: 0, y: CGRectGetMaxY(contentLabel.frame) + 5, width: CMDB_Screen_Width, height: 0)
        }
        
        if Int(topicData.likeCount) > 0 {
            
            likedView.hidden   = false
            
            showLikeViewHeight = 36
            
            likedView.frame = CGRect(x: 0, y: CGRectGetMaxY(picsView.frame), width: CMDB_Screen_Width, height: showLikeViewHeight)
            
            
            for (index,likeUser) in topicData.likeUsers!.enumerate() {
                
                let likeheadIcon = UIImageView()
                
                likeheadIcon.setHeader(likeUser.icon)
                
                likeheadIcon.frame = CGRect(x: CGRectGetMaxX(likeBtnImage.frame) + 10 + (20 + 10) * CGFloat(index), y: 10, width: 20, height: 20)
                
                likedView.addSubview(likeheadIcon)
                
                if index > 8 {
                    break
                }
            }
            separateView.frame = CGRect(x: 0, y: CGRectGetMaxY(likedView.frame), width: CMDB_Screen_Width, height: 10)

        }else{
            
            likedView.hidden = true
            
            likedView.frame = CGRect(x: 0, y: CGRectGetMaxY(picsView.frame), width: CMDB_Screen_Width, height: showLikeViewHeight)
            
            separateView.frame = CGRect(x: 0, y: CGRectGetMaxY(picsView.frame), width: CMDB_Screen_Width, height: 10)
            
        }
        
        
        
        separateView.frame = CGRect(x: 0, y: CGRectGetMaxY(picsView.frame) + showLikeViewHeight, width: CMDB_Screen_Width, height: 10)
        
        if topicData.comments?.count > 0 {
            showAllComHeight = 36
            
            showAllComView.hidden = false
            
            showAllComView.frame  = CGRect(x: 0, y: CGRectGetMaxY(separateView.frame), width: CMDB_Screen_Width, height: showAllComHeight)
            
            
        }else{
            
            showAllComView.hidden = true
            
            showAllComView.frame  = CGRect(x: 0, y: CGRectGetMaxY(separateView.frame), width: CMDB_Screen_Width, height: showAllComHeight)

            
        }

        if topicData.cellHeight == 0 {
            
            layoutIfNeeded()
            
            topicData.cellHeight = CGRectGetMaxY(contentLabel.frame) + separateView.height + 5 + pictureViewH + 10 + showLikeViewHeight + showAllComHeight + 10
            
            thisHeight           = topicData.cellHeight
        }
    }
}


extension CMDBDetailHeaderView
{
    
    func setupPictureView(imagesUrls : String){
        
        var picWidth : CGFloat = 0
        
        let picsView         = UIView.getInstance()
        
        self.picsView        = picsView
        
        self.picsView.hidden = false
        
        let imageUrlData = imagesUrls.dataUsingEncoding(NSUTF8StringEncoding)
        
        do {
            
            let urlArray = try NSJSONSerialization.JSONObjectWithData(imageUrlData!, options: .AllowFragments) as! [[String : AnyObject]]
            
            let urls       = CMDBPictureMdeol.objectArrayWithKeyValuesArray(urlArray as NSArray) as! [CMDBPictureMdeol]
            
            let picModel = urls.first
            
            for (index,pictureModel) in urls.enumerate() {
                
                let row               = index / rowCount
                
                let col               = index % rowCount
                
                let picView           = UIImageView.getInstance()
                
                picView.userInteractionEnabled = true
                
                picView.contentMode   = .Center
                
                picView.clipsToBounds = true
                
                picView.frame         = CGRect(x: KleftMargin + CGFloat(col) * (picViewWH + 5), y: CGFloat(row) * (picViewWH + picMargin), width: picViewWH, height: picViewWH)
                
                if urls.count == 1 {
                    if String.stringToInt(urls.first!.width) > maxTotalWidth && String.stringToInt(urls.first!.height) < maxTotalWidth{
                        
                        pictureViewH = CGFloat(maxTotalWidth) / CGFloat(1.3)
                        
                        picWidth     = CGFloat(maxTotalWidth)
                        
                    }else if String.stringToInt(urls.first!.height) > maxTotalWidth && String.stringToInt(urls.first!.width) < maxTotalWidth{
                        
                        pictureViewH = CGFloat(maxTotalWidth)
                        
                        picWidth     = CGFloat(maxTotalWidth) / CGFloat(1.3)
                        
                    }else if String.stringToInt(urls.first!.height) > maxTotalWidth && String.stringToInt(urls.first!.width) > maxTotalWidth{
                        
                        if String.stringToInt(urls.first!.width)  / String.stringToInt(urls.first!.height) > 1 {
                            pictureViewH = CGFloat(maxTotalWidth) / CGFloat(1.3)
                            
                            picWidth     = CGFloat(maxTotalWidth)
                            
                        }else{
                            
                            pictureViewH = CGFloat(maxTotalWidth)
                            
                            picWidth     = CGFloat(maxTotalWidth) / CGFloat(1.3)
                        }
                        
                    }else{
                        
                        let nf = NSNumberFormatter()
                        
                        nf.numberStyle = .DecimalStyle
                        
                        let height = nf.numberFromString(pictureModel.height) ?? 0
                        
                        pictureViewH = CGFloat(height.floatValue)
                        
                        let width = nf.numberFromString(pictureModel.width) ?? 0
                        
                        picWidth     = CGFloat(width.floatValue)
                        
                    }
                    
                    picView.frame         = CGRect(x: KleftMargin, y: picMargin, width: picWidth, height: pictureViewH)
                }
                
                picView.loadPicImage(pictureModel.url)
                
                picView.tag           = index
                
                self.tapGestureOnImageView(picView)
                
                picsView.addSubview(picView)
                
            }
            
            if urls.count == 1 {
                
                if String.stringToInt(urls.first!.width) > maxTotalWidth && String.stringToInt(urls.first!.height) < maxTotalWidth{
                    
                    pictureViewH = CGFloat(maxTotalWidth) / CGFloat(1.3)
                    
                    picWidth     = CGFloat(maxTotalWidth)
                }else if String.stringToInt(urls.first!.height) > maxTotalWidth && String.stringToInt(urls.first!.width) < maxTotalWidth{
                    
                    pictureViewH = CGFloat(maxTotalWidth)
                    
                    picWidth     = CGFloat(maxTotalWidth) / CGFloat(1.3)
                }else if String.stringToInt(urls.first!.height) > maxTotalWidth && String.stringToInt(urls.first!.width) > maxTotalWidth{
                    
                    if String.stringToInt(urls.first!.width)  / String.stringToInt(urls.first!.height) > 1 {
                        pictureViewH = CGFloat(maxTotalWidth) / CGFloat(1.3)
                        
                        picWidth     = CGFloat(maxTotalWidth)
                        
                    }else{
                        
                        pictureViewH = CGFloat(maxTotalWidth)
                        
                        picWidth     = CGFloat(maxTotalWidth) / CGFloat(1.3)
                    }
                    
                }else{
                    
                    pictureViewH = CGFloat(String.stringToInt((picModel?.height)!))
                    
                    picWidth     = CGFloat(String.stringToInt(picModel!.width))
                    
                }
                
            }else if  urls.count > 3 && urls.count < 7{
                
                pictureViewH = picViewWH * 2 + picMargin
                
            }else if urls.count > 1 && urls.count < 4{
                
                pictureViewH = picViewWH
                
            }else {
                
                pictureViewH = picViewWH * 3 + picMargin * 2
                
            }
            
            picsView.frame = CGRect(x: 0, y: CGRectGetMaxY(contentLabel.frame) + 5, width: CMDB_Screen_Width, height: pictureViewH + 10)
            
            addSubview(picsView)
        }catch _ as NSError{
            printLog("fail")
            
            
        }
        
    }
}


extension CMDBDetailHeaderView{
    
    func tapGestureOnImageView(imageView: UIImageView) {
        //建立手势识别器
        let gesture = UITapGestureRecognizer(target: self, action: #selector(tapOnView(_:)))
        //附加识别器到视图
        imageView.addGestureRecognizer(gesture)
    }
    
}


//MARK:  action m
extension CMDBDetailHeaderView{
    
    @objc func tapOnView(tapGes: UITapGestureRecognizer){
        
        printLog(tapGes.view?.tag)
        
        printLog("tapOnView")
    }

}
